'''
Created on 2012-3-31下午1:50:26

@author: nagat
@email:  yasenagat@gmail.com
'''
from bottle import route, run, Bottle, static_file, get, post, request, error,\
    response, Response, abort, redirect, Request, template, Route, TEMPLATES

app = Bottle()

@route('/')
def index():
    return 'this is index page!'


@route("/login")
def login():
    
    return "%s 登录成功"

@route('/hello/<name>')
def hello(name):
    return name+'，你好！'

#Dynamic Routes 动态路由，果然很神奇

#用于根据模块，跳转页面
@route('/wiki/<pagename>')           
def show_wiki_page(pagename):
    return pagename + ' page loading ...'

#用户的操作
#@route('/<action>/<user>')            # matches /follow/defnull
#def user_api(action,user):
#    
#    #逻辑
#    return user + action


#必须是int数字
@route('/object/<id:int>')
def callback1(id):
    print(isinstance(id, int))

#写自己的正则表达式,给力啊
@route('/show/<name:re:[a-z]+>')
def callback2(name):
    print(name)
    assert name.isalpha()

#@route('/static/<path:path>')
#def callback3(path):
#    print(path)
##    return static_file(path)



#处理http请求的get/post方式
#get方式也可以处理成route方式
@get('/login') # or @route('/login')
def login_form():
    return '''<form method="POST" action='/login'>
                <input name="name"     type="text" />
                <input name="password" type="password" />
                <input type='submit' value='login' />
              </form>'''

#登录提交
@post('/login') # or @route('/login', method='POST')
def login_submit():
    name     = request.forms.get('name')
    password = request.forms.get('password')
    if check_login(name, password):
        return "<p>恭喜你，登录成功了！Your login was correct</p>"
    else:
        return "<p>猪头，你登录失败了！</p>"
    
#登录验证
def check_login(name,password):
    if name=='admin' and password=='admin':
        return True
    else :
        return False


#Routing Static Files
#Static files such as images or css files are not served automatically. 
#You have to add a route and a callback to control which files get served and where to find them:
#静态文件不能自动加载，你必须增加一个路由，然后回调这个文件

#显示一个图片
@route('/static/<filename>')
def server_static(filename):
    return static_file(filename, root='D:\work\workspace2\pythonweb\img',download=False)

#下载一个图片
@route('/download/<filename>')
def down_static(filename):
    return static_file(filename, root='D:\work\workspace2\pythonweb\img',download=True)

#下载图片的另一个写法
@route('/dload/<filename:path>')
def download(filename):
    return static_file(filename, root='D:\work\workspace2\pythonweb\img', download=filename)


#配置404页面
@error(404)
def error404(error):
    print(error)
    return '大姨妈又来了，等会就能上了'


#改变默认字符集
#Changing the Default Encoding
#出错，悲剧
@route('/iso')
def get_iso():
    response.charset = 'ISO-8859-15'
    return 'This will be sent with ISO-8859-15 encoding.'

@route('/latin9')
def get_latin():
    Response.content_type = 'text/html; charset=latin9'
    return 'ISO-8859-15 is also known as latin9.'

#The abort() function is a shortcut for generating HTTP error pages.
#abort方法是一个生成http错误页面的快捷方式,试一下吧，亲
@route('/restricted')
def restricted():
    abort(401, "Sorry, access denied.")



#重定向
@route('/wrong/url')
def wrong():
    redirect("/wtr/url")

    
@route('/right/url')
@route('/wtr/url')    
def right():
    print(request.urlparts)
    print(request.urlparts[2])
    print(request.url)
    return 'ok'

# cookie的操作
@route('/welcome')
def hello_again():
    print('visited:',request.get_cookie("visited"))
    if request.get_cookie("visited"):
        return "Welcome back! Nice to see you again"
    else:
        response.set_cookie("visited", "yes")
        return "Hello there! Nice to meet you"

#Signed Cookies
#认证的cookies
#认证的cookies也是明码保存的

@route('/sign',method='post')
def sign():
    username = request.forms.get('username')
    password = request.forms.get('password')
    if (username != '' and  password != ''):
        response.set_cookie("account", username, secret='some-secret-key')
        return "Welcome %s! You are now logged in." % username
    else:
        return "Login failed."

@route('/mimi')
def restricted_area():
    username = request.get_cookie("account", secret='some-secret-key')
    if username:
        return "Hello %s. Welcome back." % username
    else:
        return "You are not logged in. Access denied."

@route('/sign_login')
def sign_login():
    return '''<form method="POST" action='/sign'>
                <input name="username"     type="text" />
                <input name="password" type="password" />
                <input type='submit' value='login' />
              </form>'''


#cookie使用
@route('/counter')
def counter():
    count = int( request.cookies.get('counter', '0') )
    count += 1
    response.set_cookie('counter', str(count))
    return 'You visited this page %d times' % count



#判断是不是ajax请求
@route('/is_ajax')
def is_ajax():
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        return 'This is an AJAX request'
    else:
        return 'This is a normal request'


#Query Variables


#通过浏览器？方式传递值，可以用这种方式获得
#/forum?id=9&page=10
@route('/forum')
def display_forum():
    forum_id = request.query.id
    page = request.query.page or '1'
    return 'Forum ID: %s (page %s)' % (forum_id, page)


#文件上传的例子
@route('/uploadform')
def upload_form():
    print('haha')
    return '''<form action="/upload" method="post" enctype="multipart/form-data">
      <input type="text" name="name" />
      <input type="file" name="data" />
      <input type='submit' value='login' />
    </form>
    '''

@route('/upload', method='POST')
def do_upload():
    name = request.forms.name
    data = request.files.data
    print(name)
    print(data)
#    if name and data and data.file:
    raw = data.file.read() # This is dangerous for big files
    filename = data.filename
    
    
    return "Hello %s! You uploaded %s (%d bytes)." % (name, filename, len(raw))
#    return "You missed a field."


@route('/my_ip')
def show_ip():
#    ip = request.environ.get('REMOTE_ADDR')
    ip = request.get('REMOTE_ADDR')
    print(request)
    # or ip = request['REMOTE_ADDR']
    return "Your IP is: %s" % ip

@route('/hi')
@route('/hi/<name>')
def hi(name='World'):
    return template('index', name=name)


#Caching
#所有的template是放在内存中的，修改本地tpl文件，不会生效，你必须执行bottle.TEMPLATES.clear()，才可以，或者重启服务器
#缓存模式在debug模式下不起作用
#Templates are cached in memory after compilation. 
#Modifications made to the template files will have no affect 
#until you clear the template cache. 
#Call bottle.TEMPLATES.clear() to do so. Caching is disabled in debug mode.

@route('/clear')
def clear():
    TEMPLATES.clear()
    return hi('haha')

#启动服务
run()
#可以订制端口号
#run(app, host='127.0.0.1', port=80, debug=True)





